from flask import Blueprint,jsonify,current_app,make_response
from db import db
import datetime,re,random
from flask import current_app as app,request
from flask_restful import reqparse,Api,Resource
from utils.my_rong import Sms
from utils.my_redis import MyRedis
from utils.my_jwt import MyJwt
from utils.captcha.captcha.captcha import captcha
from job.tasks.mytask import send_message

user_blue = Blueprint('user_blue',__name__,url_prefix='/user')
api = Api(user_blue)
@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    app.logger.error(str)
    app.logger.info('info log')
    app.logger.warning('warning log')
    
    sql = "insert into user values(0,'aa22222','abc')"
    db.update(sql)
    db.commit()
    sql1 = "select * from user"
    res = db.find_all(sql1)
    print(res)
    return 'ok234234'


# 发送验证码
@user_blue.route('/sendcode')
def sendcode():
    req = reqparse.RequestParser()
    req.add_argument('mobile', required=True)
    req.add_argument('uuid',required=True)
    req.add_argument('code',required=True)
    args = req.parse_args()
    # 手机验证
    rule = r'^1[3-9]\d{9}$'
    ru = re.findall(rule, args['mobile'])
    if not ru:
        return jsonify({
            "code": 400,
            "msg": '手机号格式错误'
        })

    oldcode = MyRedis().get_str(args['uuid'])
    if oldcode.decode().lower() != args['code'].lower():
        return jsonify({
            "code":400,
            "msg":'图片验证码不对，无法发送短信'
        })

    code = random.randint(100000, 999999)

    key = 'sms_%s'%args['mobile']
    newcode = MyRedis().get_str(key)
    if newcode:
        return jsonify({
            "code":400,
            "msg":'1分钟不能重复发'
        })
    else:
        MyRedis().set_str(key,code,300)
        send_message.delay(args['mobile'],code)
        return jsonify({
            "code": 200,
            "msg": '发送成功'
        })


# 图片验证码
@user_blue.route('/imagecode')
def imagecode():
    uuid = request.args.get('uuid')
    name,text,image = captcha.generate_captcha()
    res = make_response(image)
    res.headers['Content-Type'] = 'image/jpg'
    # 存入redis
    MyRedis().set_str(uuid,text)
    return res


# 登陆
class LoginView(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('mobile',required=True)
        req.add_argument('code',required=True)
        args = req.parse_args()

        if not all([args['mobile'],args['code']]):
            return jsonify({
                "code":400,
                "msg":'参数填写完整'
            })
        key = 'sms_%s'%args['mobile']
        rs = MyRedis().get_str(key)
        if not rs:
            return jsonify({
                "code":400,
                "msg":'验证码过期'
            })
        if rs.decode()!=args['code']:
            return jsonify({
                "code":400,
                "msg":'验证码错误'
            })
        sql = "select * from user where phone=%s"%args['mobile']
        rs = db.find(sql)


        # 没有用户
        if not rs:
            sql = "insert into user(name,phone) values(%s,%s)"%(args['mobile'],args['mobile'])
            db.update(sql)
            db.commit()

        sql = "select * from user where phone=%s" % args['mobile']
        rs = db.find(sql)

        payload = {'data':{
            "id":rs['id'],
            'name':rs['phone']
        }}
        token = MyJwt().jwt_encode(payload)
        return jsonify({
            "code":200,
            "msg":'登录成功',
            "data":{
                'token':token,
                "id":rs['id'],
                "name":rs['name']
            }
        })

api.add_resource(LoginView,'/login')


# 员工管理，添加获取列表
@user_blue.route('/empManger',methods=['POST','GET'])
def empManger():
    pass


@user_blue.route('/get_wb')
def get_weibo():
    client_id= '3674019597'
    redirect_uri= 'http://127.0.0.1:8000/user/weiboCallback/'  # VU
    url = "http://api.weibo.com/oauth2/authorize?client_id=%s&response"

    return jsonify({
        'url':url
    })


